package com.auto.api.common.utils;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * @program:
 * @description: Dozer BeanMapper 对象转换
 * @author: liangshf
 * @create: 2022-01-05
 */
public class BeanMapper {

    private static Mapper mapper = DozerBeanMapperBuilder.buildDefault();

    public static <T> T map(Object source, Class<T> desClass) {
        if (source == null) {
            return null;
        }
        return mapper.map(source, desClass);
    }

    public static <T> T map(Object source, Class<T> desClass, Consumer<T> consumer) {
        T result = map(source, desClass);
        consumer.accept(result);
        return result;
    }

    public static <T> List<T> mapList(Collection<?> sourceList, Class<T> desClass) {
        if (sourceList == null) {
            return null;
        }
        List<T> desList = Lists.newArrayListWithCapacity(sourceList.size());
        for (Object source : sourceList) {
            desList.add(map(source, desClass));
        }
        return desList;
    }

    public static <T,S> List<T> mapList(Collection<S> sourceList, Class<T> desClass, BiConsumer<S,T> consumer) {
        if (sourceList == null) {
            return null;
        }
        List<T> desList = Lists.newArrayListWithCapacity(sourceList.size());
        for (S source : sourceList) {
            T desObj = map(source, desClass);
            consumer.accept(source, desObj);
            desList.add(desObj);
        }
        return desList;
    }
}